<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String path = request.getContextPath() ;%>
<!DOCTYPE html>
<html lang="en">
<head>
	<title>大文件上传测试页</title>
	<jsp:include page="../../import.jsp" flush="true" />
    <script type="text/javascript" src="//cdn.staticfile.org/webuploader/0.1.5/webuploader.min.js" charset="utf-8">
	</script>
	<script src="//cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
	<style type="text/css">
		.webuploader-container {
			position: relative;
		}
		.webuploader-element-invisible {
			position: absolute !important;
			clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
		    clip: rect(1px,1px,1px,1px);
		}
		.webuploader-pick {
			position: relative;
			display: inline-block;
			cursor: pointer;
			background: #00b7ee;
			padding: 10px 15px;
			color: #fff;
			text-align: center;
			border-radius: 3px;
			overflow: hidden;
		}
		.webuploader-pick-hover {
			background: #00a2d4;
		}
		
		.webuploader-pick-disable {
			opacity: 0.6;
			pointer-events:none;
		}
		.itemDel, .itemStop, .itemUpload{
			margin-left: 15px;
			color: blue;
			cursor: pointer;
		}
		#theList{
			width: 80%;
			min-height: 100px;
			border: 1px solid red;
		}
        #theList .itemStop{
            display: none;
        }
	</style>
</head>
<body>
    <body>
		<div id="uploader">
			<ul id="theList"></ul>
			<div id="picker">选择文件</div>
		</div>
		<script type="text/javascript">
            var filePath = '/tillfile/';
		   	var userInfo = {userId:"kazaff", md5:"", filePath:filePath}; 
            var chunkSize = 5000 * 1024;        //分块大小
            var originFileName = null;          //原始文件名称
            var uniqueFileName = null;          //文件唯一标识符
            var fileExt = null;
            var md5Mark = null;
            
            var backEndUrl = '<%=path%>/system/sysulfilesrec/tillFileUpload.do';
            var backStatusUrl = '<%=path%>/system/sysulfilesrec/tillFileUploadStatus.do';
            WebUploader.Uploader.register({
                "before-send-file": "beforeSendFile"
                , "before-send": "beforeSend"
                , "after-send-file": "afterSendFile"
            }, {
                beforeSendFile: function(file){
                	originFileName = file.name;
                	fileExt = file.ext;
                    uniqueFileName = md5(''+userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size);
                	md5Mark = uniqueFileName;
                    userInfo.md5 = uniqueFileName;
                }
                , beforeSend: function(block){
                    //分片验证是否已传过，用于断点续传
                    var task = new $.Deferred();
                    $.ajax({
                        type: "POST"
                        , url: backStatusUrl
                        , data: {
                            status: "chunkCheck"
                            , originFileName: originFileName
                            , fileName: uniqueFileName
                            , chunkIndex: block.chunk
                            , size: block.end - block.start
                            , filePath:filePath
                        }
                        , cache: false
                        , timeout: 5000 //todo 超时的话，只能认为该分片未上传过
                        , dataType: "json"
                    }).then(function(data, textStatus, jqXHR){
                        	//alert(JSON.stringify(data) + data.success)
                        	
                        	 if(data.success == 2){   //若存在，返回失败给WebUploader，表明该分块不需要上传
                                    task.resolve();
                                 }else{
                                	 task.reject();
                                 }	
                       	 	
                       
                       /*  if(data.ifExist){   //若存在，返回失败给WebUploader，表明该分块不需要上传
                        //if(data.success){   //若存在，返回失败给WebUploader，表明该分块不需要上传
                            task.reject();
                        }else{
                            task.resolve();
                        } */
                    }, function(jqXHR, textStatus, errorThrown){    //任何形式的验证失败，都触发重新上传
                        task.resolve();
                    });
                    return $.when(task);
                }
                , afterSendFile: function(file){
                    var chunksTotal = 0;
                    if((chunksTotal = Math.ceil(file.size/chunkSize)) > 1){
                        //合并请求
                        var task = new $.Deferred();
                        $.ajax({
                            type: "POST"
                            , url: backStatusUrl
                            , data: {
                                status: "chunksMerge"
                                , originFileName: originFileName
                                , fileName: uniqueFileName
                                , chunks: chunksTotal
                                , ext: file.ext
                                , md5: md5Mark
                                , filePath:filePath
                            }
                            , cache: false
                            , dataType: "json"
                        }).then(function(data, textStatus, jqXHR){
                            //todo 检查响应是否正常
                            debugger; //TODO 这里可以接收到最终路径结果 
                            task.resolve();
                            file.path = data.path;
                            UploadComlate(file);
                        }, function(jqXHR, textStatus, errorThrown){
                            task.reject();
                        });
                        return $.when(task);
                    }else{
                        UploadComlate(file);
                    }
                }
            });
            
            //console.log(JSON.stringify(data));
			var uploader = WebUploader.create({
				swf: "Uploader.swf"
				, server: backEndUrl
				, pick: "#picker"
				, resize: false
				, dnd: "#theList"
				, paste: document.body
				, disableGlobalDnd: true
				, thumb: {
					width: 100
					, height: 100
					, quality: 70
					, allowMagnify: true
					, crop: true
					//, type: "image/jpeg"
				}
                , compress: false
				, prepareNextFile: true
				, chunked: true
				, chunkSize: chunkSize
				, threads: 3
				, formData: $.extend(true, {}, userInfo)
				, fileNumLimit: 1
				, fileSingleSizeLimit: 1000 * 1024 * 1024
				, duplicate: true
			});
			uploader.on("fileQueued", function(file){
				$("#theList").append('<li id="'+file.id+'">' +
					'<img /><span>'+file.name+'</span><span class="itemUpload">上传</span><span class="itemStop">暂停</span><span class="itemDel">删除</span>' +
					'<div class="percentage"></div>' +
				'</li>');
				var $img = $("#" + file.id).find("img");
				uploader.makeThumb(file, function(error, src){
					if(error){
						$img.replaceWith("<span>不能预览</span>");
					}
					$img.attr("src", src);
				});
			});
			uploader.on('uploadBeforeSend', function(block, data, headers) {
	            // 修改data可以控制发送哪些携带数据。
	            data.originFileName = originFileName;
	            data.fileName = uniqueFileName;
	            data.ext = fileExt;
	        });
			$("#theList").on("click", ".itemUpload", function(){
				uploader.upload();
                //"上传"-->"暂停"
                $(this).hide();
                $(".itemStop").show();
			});
            $("#theList").on("click", ".itemStop", function(){
                uploader.stop(true);
                //"暂停"-->"上传"
                $(this).hide();
                $(".itemUpload").show();
            });
            //todo 如果要删除的文件正在上传（包括暂停），则需要发送给后端一个请求用来清除服务器端的缓存文件
			$("#theList").on("click", ".itemDel", function(){
				uploader.removeFile($(this).parent().attr("id"));	//从上传文件列表中删除
				$(this).parent().remove();	//从上传列表dom中删除
			});
			uploader.on("uploadProgress", function(file, percentage){
				$("#" + file.id + " .percentage").text(percentage * 100 + "%");
			});
            function UploadComlate(file){
                $("#" + file.id + " .percentage").text("上传完毕");
                $(".itemStop").hide();
                $(".itemUpload").hide();
                $(".itemDel").hide();
            }
		</script>
	</body>
</html>
